import type { ValuesType, AssetLampPostStateType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { shareEnum } from '~/store/base/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElButton,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { Plus, Delete, EditPen } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AssetLampPostOptions from './option'
import styles from '~/pages/assetManagement/index.module.scss'
import ExportExcel from '~/components/ExportExcel'
import ImportExcel from './ImportExcel'
import ImportExcelSurvey from './ImportExcelSurvey'
import DemandBatch from './DemandBatch'
import { isURL } from '~/utils/validate'

export default defineComponent(function BasestationConstruction() {
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const state = reactive<AssetLampPostStateType>({
    importVisible: false, // 导入 弹窗是否显示
    exportVisible: false, // 导出 弹窗是否显示
    modalVisible: false, // 新增/编辑 弹窗是否显示
    inputShow: false,
    needVisible: false,
    importSurveyVisible: false, //  更新查勘状态 弹窗是否显示
    type: 'read',
    record: {},
    batchNumType: 'text',
    demandBatchVisible: false,
    batchNum: ''
  })
  const userState = useVuexGetters('user', ['permission']) // 按钮权限
  const baseState = useVuexGetters('base', [
    'isMatchOpt',
    'regionNameOpt',
    'surveyStatusOpt',
    'duplicateOpt',
    'operatorOpt'
  ])
  const store = useStore()
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '站点名称',
      prop: 'matchName',
      showOverflowTooltip: true,
      minWidth: 200,
      fixed: 'left',
      unFixed: true,
      sortable: true, //  排序
      disabled: true, //  不可编辑
      render: ({ row }) => (
        <ElLink type="primary" onClick={() => infoOpen(row)}>
          {row.matchName}
        </ElLink>
      )
    },
    {
      label: '灯杆名称',
      prop: 'name',
      showOverflowTooltip: true,
      minWidth: 200,
      // fixed: 'left',
      // unFixed: true,
      sortable: true //  排序
      // disabled: true //  不可编辑
    },
    {
      label: '需求批次',
      prop: 'batchNum',
      minWidth: 160,
      sortable: true,
      render: ({ row }) => (
        <ElLink type="primary" onClick={() => handBatchNumModal(row)}>
          {row.batchNum}
        </ElLink>
      )
    },
    {
      label: '建设类型',
      prop: 'buildType',
      minWidth: 140,
      sortable: true,
      render: (_, value) => {
        return (
          <>
            {value === 1 ? (
              <div style="color: #03B615;">新建</div>
            ) : (
              <div style="color: #4073FF;">搬迁</div>
            )}
          </>
        )
      }
    },
    {
      label: '所属区分',
      prop: 'buildArea',
      minWidth: 160,
      sortable: true
    },
    {
      label: '所属地区',
      prop: 'regionName',
      minWidth: 220,
      sortable: true
    },
    {
      label: '查勘状态',
      prop: 'isSurvey',
      showOverflowTooltip: true,
      minWidth: 160,
      sortable: true,
      render: (_, value) => {
        return <>{isSurveyChange(value)}</>
      }
    },
    {
      label: '查看全景',
      prop: 'overallViewUrl',
      width: 88,
      align: 'center',
      sortable: false,
      render: ({ row }) => (
        <>
          {isURL(row.overallViewUrl) ? (
            <a href={row.overallViewUrl} target="_blank" style="cursor: pointer; color: blue;">
              查看全景
            </a>
          ) : (
            '-'
          )}
        </>
      )
    },
    {
      label: '是否重复',
      prop: 'isRepeat',
      minWidth: 160,
      align: 'center',
      sortable: true,
      render: (_, value) => {
        return <>{value === 1 ? '是' : '否'}</>
      }
    },
    // {
    //   label: '备注',
    //   prop: 'memo',
    //   minWidth: 160,
    //   sortable: true
    // },
    {
      label: '所属省',
      prop: 'provinceName',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '所属市',
      prop: 'cityName',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '站点经度',
      prop: 'lon',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '站点纬度',
      prop: 'lat',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '站点地址',
      prop: 'address',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '规划站号',
      prop: 'matchNum',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '需求类型',
      prop: 'requirementType',
      minWidth: 160,
      sortable: true,
      hidden: true,
      render: ({ row }) => (
        <>{row.requirementType === 2 ? <div style="color: blue;">特批</div> : '常规'}</>
      )
    },
    {
      label: '需求备注',
      prop: 'requirementMemo',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '运营商',
      prop: 'infoServer',
      minWidth: 160,
      sortable: true,
      hidden: true,
      render: ({ row }) => (
        <>
          {row.infoServer === 1 && <div style="color: #0085D0;">移动</div>}
          {row.infoServer === 2 && <div style="color: #00489D;">电信</div>}
          {row.infoServer === 3 && <div style="color: #D80A17;">联通</div>}
        </>
      )
    },
    {
      label: '查勘批次',
      prop: 'surveyorNum',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '查勘人',
      prop: 'surveyorName',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '查勘备注',
      prop: 'surveyorMemo',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '更新人',
      prop: 'updateUser',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '创建人',
      prop: 'createUser',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '创建时间',
      prop: 'createTime',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '摘牌结果',
      prop: 'delistingRes',
      minWidth: 160,
      sortable: true,
      hidden: true,
      render: ({ row }) => (
        <>
          {row.delistingRes === 1 && <div style="color: #D9001B;">未投标</div>}
          {row.delistingRes === 2 && <div style="color: red;">中标</div>}
          {row.delistingRes === 3 && <div style="color: #4073ff;">流标</div>}
        </>
      )
    },
    {
      label: '承建商',
      prop: 'contractor',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '实际折扣率(%)',
      prop: 'reaDiscount',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '流标原因分类',
      prop: 'abortiveType',
      minWidth: 160,
      sortable: true,
      hidden: true,
      render: ({ row }) => (
        <>
          {row.abortiveType === 1 && <div>不满足建设条件</div>}
          {row.abortiveType === 2 && <div>其它公司已建</div>}
          {row.abortiveType === 3 && <div>价格因素</div>}
          {row.abortiveType === 4 && <div>排名</div>}
        </>
      )
    },
    {
      label: '流标原因',
      prop: 'abortiveReson',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '建设交付情况',
      prop: 'completeMemo',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '要求交付时间',
      prop: 'deliveryTime',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 180,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true, //  不可编辑
      width: 220,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('station_basebuild_view') && (
            <ElLink type="primary" onClick={() => infoOpen(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情&nbsp;&nbsp;
            </ElLink>
          )}
          {userState.permission.value.has('station_basebuild_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('station_basebuild_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    //  是否共享
    store.dispatch('base/ShareGet', { code: 'asset_station_share' })
    //  基站状态
    store.dispatch('base/BaseStatusGet', { code: 'asset_station_isdeliver' })
    //  站点类型
    store.dispatch('base/SiteTypeGet', { code: 'asset_station_type' })
    //  是否匹配
    store.dispatch('base/IsMatchGet', { code: 'asset_station_match' })
    //  基站勘测状态
    store.dispatch('base/SurveyStatusGet', { code: 'asset_station_survey' })
    //  建设类型
    store.dispatch('base/BuildGet', { code: 'asset_station_build_type' })
    //  运营商
    store.dispatch('base/OperatorGet', { code: 'asset_station_build_infoserver' })
    //  需求类型
    store.dispatch('base/DemandTypeGet', { code: 'asset_station_requirement_type' })
  })

  //  查勘状态
  const isSurveyChange = (value: number) => {
    let str: any = ''
    if (value === 0) {
      str = <div>待查勘</div>
    }
    if (value === 1) {
      str = <div style="color: #4073FF;">匹配</div>
    }
    if (value === 2) {
      str = <div style="color: #D9001B;">不匹配</div>
    }
    return str
  }

  // 新增/编辑
  const handleChangeOptionsModal = (type: AssetLampPostStateType['type'], record?: ValuesType) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  const handleDeleteSelectedData = async (params: string) => {
    await store
      .dispatch('base/GetBasebuildRemove', {
        ids: params
      })
      .then((res) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: ValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        handleDeleteSelectedData(params)
      })
      .catch(() => {})
  }

  //  详情
  const infoOpen = (record: ValuesType) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = 'read'
  }

  // 导出
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  //  关键字搜索
  const remoteMethod = async (query: string) => {
    if (query) {
      const { code, data } = await store.dispatch('base/GetSelectBatchNumListBox', {
        batchNum: query
      })
      if (code === 200) {
        state.SelectListCode = data
      } else {
        state.SelectListCode = []
      }
    }
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  //   灯杆名称/站点名称
  const rowsNum = ref(1)
  const onNameFocus = () => {
    rowsNum.value = 4
  }
  const onNameBlur = () => {
    rowsNum.value = 1
  }

  //  需求批次显瘾
  const handBatchNumModal = (record?: ValuesType) => {
    state.demandBatchVisible = !state.demandBatchVisible
    state.record = record || {}
  }

  return () => {
    if (state.modalVisible) {
      return (
        <AssetLampPostOptions
          record={state.record}
          type={state.type}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }
    if (state.demandBatchVisible) {
      return <DemandBatch record={state.record} cancel={() => handBatchNumModal()} />
    }

    return (
      <ElCard>
        <ProSaasTable<ValuesType>
          tableId="baseConstruction"
          ref={proSaasTableRef}
          rowKey="id"
          hasSelection
          rowClickSelection
          columns={columns}
          searchParams={{
            isSurvey: formValues.isSurvey?.join(','),
            batchNum: formValues.batchNum?.join(',')
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="base/GetBasebuildList"
          headerTitle={
            <>
              {userState.permission.value.has('station_basebuild_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {userState.permission.value.has('station_basebuild_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
              {userState.permission.value.has('station_basebuild_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <ElIcon>
                    <Delete />
                  </ElIcon>
                  &nbsp; 删除
                </ElButton>
              )}
              {userState.permission.value.has('station_basebuild_import') && (
                <ElButton
                  type="primary"
                  onClick={() => {
                    state.importVisible = true
                  }}
                >
                  <AliIcon type="icon-daoru" />
                  &nbsp; 导入
                </ElButton>
              )}
              {userState.permission.value.has('station_basebuild_update_import') && (
                <ElButton
                  type="primary"
                  onClick={() => {
                    state.importSurveyVisible = true
                  }}
                >
                  <AliIcon type="icon-daoru" />
                  &nbsp; 更新查勘状态
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="batchNum" prop="batchNum" label="">
              <ElSelect
                v-model={formValues.batchNum}
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="需求批次"
                filterable
                remote
                reserve-keyword
                remote-method={remoteMethod}
                onChange={clearSearchTable}
              >
                {state.SelectListCode?.map((item: string) => (
                  <ElOption key={item} label={item} value={item} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="name" prop="name" label="">
              <ElInput
                v-model={formValues.name}
                {...{ rows: rowsNum.value }}
                placeholder="灯杆名称/站点名称"
                onKeydown={handleKeyDownEnterSubmitForm}
                onFocus={onNameFocus}
                onBlur={onNameBlur}
                type="textarea"
                style="position: absolute; top: 0; z-index: 99;"
              />
            </ElFormItem>,
            <ElFormItem key="buildArea" prop="buildArea" label="">
              <ElInput
                v-model={formValues.buildArea}
                {...{ maxlength: 30 }}
                placeholder="所属区分"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="surveyorName" prop="surveyorName" label="">
              <ElInput
                v-model={formValues.surveyorName}
                {...{ maxlength: 30 }}
                placeholder="查勘人"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="infoServer" prop="infoServer" label="">
              <ElSelect
                v-model={formValues.infoServer}
                clearable
                onChange={clearSearchTable}
                placeholder="运营商"
              >
                {baseState.operatorOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="isSurvey" prop="isSurvey" label="">
              <ElSelect
                v-model={formValues.isSurvey}
                clearable
                multiple
                onChange={clearSearchTable}
                placeholder="查勘状态"
              >
                {baseState.surveyStatusOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="isRepeat" prop="isRepeat" label="">
              <ElSelect
                v-model={formValues.isRepeat}
                clearable
                onChange={clearSearchTable}
                placeholder="是否重复"
              >
                {baseState.isMatchOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="dupl" prop="dupl" label="">
              <ElSelect
                v-model={formValues.dupl}
                clearable
                onChange={clearSearchTable}
                placeholder="去重"
              >
                {baseState.duplicateOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>
            // <ElFormItem key="matchName" prop="matchName" label="">
            //   <ElInput
            //     v-model={formValues.matchName}
            //     {...{ maxlength: 30 }}
            //     placeholder="请输入匹配站名"
            //     clearable
            //     onKeydown={handleKeyDownEnterSubmitForm}
            //     onClear={clearSearchTable}
            //   />
            // </ElFormItem>,
          ]}
        ></ProSaasTable>
        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="base/BasebuildExport"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{
              params: {
                ...formValues,
                batchNum: formValues.batchNum?.join(','),
                isSurvey: formValues.isSurvey?.join(',')
              }
            }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}

        {/* 导入 */}
        {state.importVisible && (
          <ImportExcel
            onHandleImportFile={() => {
              proSaasTableRef.value?.toSearch()
            }}
            doCancel={() => {
              state.importVisible = false
            }}
          />
        )}

        {/* 更新查勘状态 */}
        {state.importSurveyVisible && (
          <ImportExcelSurvey
            onHandleImportFile={() => {
              proSaasTableRef.value?.toSearch()
            }}
            doCancel={() => {
              state.importSurveyVisible = false
            }}
          />
        )}
      </ElCard>
    )
  }
})
